/*  ----------------------------------------------------------------------------
 *  Arello Mobile
 *  Fast 3d Engine
 *  ----------------------------------------------------------------------------
 * Except where otherwise noted, this work is licensed under
 * http://creativecommons.org/licenses/by/3.0
 */

#include <logs/Log.h>
#include "ForceEffect.h"
#include "Joystick.h"
#include <win32/win32.h>

namespace liba
{
namespace input
{
namespace hard
{
namespace directx8
{

BOOL CALLBACK ForceEffect::EnumEffectsInFileProc( LPCDIFILEEFFECT lpdife, LPVOID pvRef)
{
    ForceEffect* obj = reinterpret_cast<ForceEffect*>(pvRef);

    LPDIRECTINPUTEFFECT  lpdiEffect=0;      // Pointer to created effect

    int res = 0;
	if( res = obj->device->CreateEffect(lpdife->GuidEffect,
			lpdife->lpDiEffect,
		    &lpdiEffect,
			NULL) == DI_OK )
	{
		obj->effects.push_back(lpdiEffect);
	}
	else
		logs::log() << logs::warning << "effect not created, res=" << res << "\n";
    return DIENUM_CONTINUE;
}

bool ForceEffect::stop()
{
	Effects::iterator i = effects.begin();
	Effects::iterator end = effects.end();
	for( ;i != end; ++i )
	{
		DWORD pdwFlags = 0;
		if( SUCCEEDED( (*i)->GetEffectStatus( &pdwFlags ) ) )
			if( pdwFlags & DIEGES_PLAYING  )
				(*i)->Stop();
	}
	return true;	
}

bool ForceEffect::play()
{
	Effects::iterator i = effects.begin();
	Effects::iterator end = effects.end();
	for( ;i != end; ++i )
	{
		DWORD pdwFlags = 0;
		if( SUCCEEDED( (*i)->GetEffectStatus( &pdwFlags ) ) )
		{
			if( !( pdwFlags & DIEGES_PLAYING ) )
				(*i)->Start( 1, 0 );
		}
	}
	return true;
}

bool ForceEffect::is_playing()
{
	Effects::iterator i = effects.begin();
	Effects::iterator end = effects.end();
	for( ;i != end; ++i )
	{
		DWORD pdwFlags = 0;
		if( SUCCEEDED( (*i)->GetEffectStatus( &pdwFlags ) ) )
		{
			if(  pdwFlags & DIEGES_PLAYING )
				return true;				
		}
	}
	return false;
}


ForceEffect::~ForceEffect()
{	
	stop();
	Effects::iterator i = effects.begin();
	Effects::iterator end = effects.end();
	for( ;i != end; ++i)
	{
		(*i)->Release();*i=0;
	}
	device->Release();device=0;
}

ForceEffect::ForceEffect(IDirectInputDevice8 * device, const filesystem::String & effect_name ):
	device( device )
{
	device->AddRef();
	int res = device->EnumEffectsInFile( (effect_name + ".ffe").c_str(), 
		EnumEffectsInFileProc,
        this, 
        DIFEF_MODIFYIFNEEDED);
}

} // namespace directx8
} // namespace hard
} // namespace input
} // namespace liba


